package net.wesley.android.city;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import net.wesley.android.City;

public class WuHan extends City {

	public void requestParamsFinish(String[] values) {
		final DefaultHttpClient httpClient = new DefaultHttpClient();  
		try {
			HttpGet get = new HttpGet("http://wh122.cjn.cn/");
			httpClient.execute(get);
			
			HttpResponse rsp = httpClient.execute(new HttpGet("http://wh122.cjn.cn/gcode.act"));			
			Bitmap bmp= BitmapFactory.decodeStream(rsp.getEntity().getContent());
			LinearLayout table=new LinearLayout(ctx);
			table.setOrientation(LinearLayout.VERTICAL);
			ImageView v=new ImageView(ctx);
			v.setImageBitmap(bmp);
			v.setScaleType(ImageView.ScaleType.FIT_XY);
			LayoutParams p = new LinearLayout.LayoutParams(200,50);
			p.gravity=Gravity.CENTER;
			table.addView(v,p);
			final EditText t=new EditText(ctx);
			table.addView(t,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
			new AlertDialog.Builder(ctx).setTitle("请输入下图中的验证码").setView(table).setNegativeButton("确定", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					new Handler().postDelayed(new Runnable(){

						public void run() {
							HttpPost post=new HttpPost("http://wh122.cjn.cn/vehcile.act");
							try {
								post.setEntity(new StringEntity(String.format("shjc=%s&lb=A&carNo=%s&carType=XQ&imageCode=%s&clwz.x=17&clwz.y=5",
										URLEncoder.encode("鄂","gbk"),chepai.substring(1),t.getText().toString())));
								post.setHeader("Content-Type","application/x-www-form-urlencoded");
								post.setHeader("Referer", "http://wh122.cjn.cn");
								HttpResponse rsp = httpClient.execute(post);
								BufferedReader br;
								br = new BufferedReader(new InputStreamReader(rsp.getEntity()
										.getContent(),"GBK"));
								String line, result = "";
								while ((line = br.readLine()) != null) result += line+"\n";
								processResult(result);
							} catch (UnsupportedEncodingException e) {
								callback.onComplete(-10003, "");
							} catch (ClientProtocolException e) {
								callback.onComplete(-10004, "");
							} catch (IOException e) {
								callback.onComplete(-10005, "");
							}
						}
						
					}, 1000);
				}
			}).create().show();
		} catch (ClientProtocolException e) {
			callback.onComplete(-10001, "");
		} catch (IOException e) {
			callback.onComplete(-10002, "");
		}
	}

	protected void processResult(String str) {
		String[] errstr={"对不起，附加码输入有误！","系统繁忙，查询超时！"};
		for (int i=0;i<errstr.length;i++){
			String err=errstr[i];
			if (str.indexOf(err)>=0){
				callback.onComplete(-10001, err);
				return;
			}
		}
		int total=0;
		String retvalue="";
		while (str.indexOf("违章时间")>0){
			String shijian = str.split("违章时间")[1].split("<td")[1].split(">")[1].split("<")[0].trim().replace("&nbsp;","");
			String didian = str.split("违章地点")[1].split("<td")[1].split(">")[1].split("<")[0].trim().replace("&nbsp;","");
			String code = str.split("违章事由")[1].split("<td")[1].split(">")[1].split("<")[0].trim().replace("&nbsp;","");
			retvalue+=String.format("shijian:%s\ndidian:%s\ncode:%s\n\n" ,shijian,didian,code);
			total+=1;
			str=str.split("违章事由",1)[1];
		}
		callback.onComplete(total, retvalue);
	}

	@Override
	public boolean match(String chepai) {
		return chepai.startsWith("鄂A");
	}

	@Override
	public String[] paramDesc() {
		return null;
	}

}
